package com.wxscrmplus.marketing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.marketing.domain.MarMsgAttachments;
import com.wxscrmplus.marketing.domain.MarWelcomeMessage;
import com.wxscrmplus.marketing.domain.bo.MarWelcomeMessageBo;
import com.wxscrmplus.marketing.domain.vo.MarWelcomeMessageVo;
import com.wxscrmplus.marketing.mapper.MarCategoryMapper;
import com.wxscrmplus.marketing.mapper.MarMsgAttachmentsMapper;
import com.wxscrmplus.marketing.mapper.MarWelcomeMessageMapper;
import com.wxscrmplus.marketing.service.IMarWelcomeMessageService;
import com.wxscrmplus.wxcp.factory.WxCpServiceFactory;
// 55f9223fc5a466bf1163637370cd7215
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.external.WxCpWelcomeMsg;
import me.chanjar.weixin.cp.bean.external.msg.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 欢迎语Service业务层处理
 *
 * @author 王永超
 * @date 2023-05-07
 */
@RequiredArgsConstructor
@Service
public class MarWelcomeMessageServiceImpl extends WxCpServiceFactory implements IMarWelcomeMessageService {

    private final MarWelcomeMessageMapper baseMapper;
    private final MarCategoryMapper categoryMapper;
    private final MarMsgAttachmentsMapper marMsgAttachmentsMapper;

    /**
     * 查询欢迎语
     */
    @Async
    @Override
    public void send(Long welcomeMsgId, String welcomeCode) {
        MarWelcomeMessageVo marWelcomeMessageVo = baseMapper.selectVoById(welcomeMsgId);
        List<MarMsgAttachments> welcomeAttachmentsList = marMsgAttachmentsMapper.selectList(Wrappers.query(new MarMsgAttachments()).lambda()
            .eq(MarMsgAttachments::getTargetType, MarMsgAttachments.TargetTypeFieldEnums.ONE.getValue())
            .eq(MarMsgAttachments::getTargetId, marWelcomeMessageVo.getWelcomeMsgId()));
        List<Attachment> attachmentList = new ArrayList<>();
        for (MarMsgAttachments marWelcomeAttachments : welcomeAttachmentsList) {
            Attachment attachment = new Attachment();
            JSONObject attContent = marWelcomeAttachments.getAttContent();
            switch (marWelcomeAttachments.getMsgtype()) {
                case WxConsts.MediaFileType.IMAGE:
                    if (ObjectUtil.isNotNull(attContent.get("mediaId"))) {
                        Image image = new Image();
                        image.setMediaId(attContent.getStr("mediaId"));
                        attachment.setImage(image);
                        attachmentList.add(attachment);
                    }
                    break;
                case WxConsts.MediaFileType.VIDEO:
                    if (ObjectUtil.isNotNull(attContent.get("mediaId"))) {
                        Video video = new Video();
                        video.setMediaId(attContent.getStr("mediaId"));
                        attachment.setVideo(video);
                        attachmentList.add(attachment);
                    }
                    break;
                case WxConsts.MediaFileType.FILE:
                    if (ObjectUtil.isNotNull(attContent.get("mediaId"))) {
                        File file = new File();
                        file.setMediaId(attContent.getStr("mediaId"));
                        attachment.setFile(file);
                        attachmentList.add(attachment);
                    }
                    break;
                case "link":
                    Link link = new Link();
                    link.setTitle(attContent.getStr("title"));
                    link.setDesc(attContent.getStr("desc"));
                    link.setUrl(attContent.getStr("url"));
                    link.setPicUrl(attContent.getStr("picurl"));
                    attachment.setLink(link);
                    attachmentList.add(attachment);
                    break;
            }
        }
        WxCpWelcomeMsg wxCpWelcomeMsg = new WxCpWelcomeMsg();
        wxCpWelcomeMsg.setWelcomeCode(welcomeCode);
        Text text = new Text();
        text.setContent(marWelcomeMessageVo.getMessage());
        wxCpWelcomeMsg.setText(text);
        wxCpWelcomeMsg.setAttachments(attachmentList);
        try {
            getExternalContactService().sendWelcomeMsg(wxCpWelcomeMsg);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询欢迎语
     */
    @Override
    public MarWelcomeMessageVo queryById(Long welcomeMsgId) {
        return baseMapper.selectVoById(welcomeMsgId);
    }

    /**
     * 查询欢迎语列表
     */
    @Override
    public TableDataInfo<MarWelcomeMessageVo> queryPageList(MarWelcomeMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MarWelcomeMessage> lqw = buildQueryWrapper(bo);
        Page<MarWelcomeMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<MarWelcomeMessageVo> records = result.getRecords();
        for (MarWelcomeMessageVo record : records) {
            record.setCategoryLabel(categoryMapper.findNameById(record.getCategoryId()));
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询欢迎语列表
     */
    @Override
    public List<MarWelcomeMessageVo> queryList(MarWelcomeMessageBo bo) {
        LambdaQueryWrapper<MarWelcomeMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MarWelcomeMessage> buildQueryWrapper(MarWelcomeMessageBo bo) {
        Set<Long> categoryIdList = new HashSet<>();
        if (ObjectUtil.isNotNull(bo.getCategoryId())) {
            categoryIdList.add(bo.getCategoryId());
        }
        if (CollUtil.isNotEmpty(bo.getCategoryIdList())) {
            categoryIdList.addAll(bo.getCategoryIdList());
        }
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MarWelcomeMessage> lqw = Wrappers.lambdaQuery();
        lqw.in(CollUtil.isNotEmpty(categoryIdList), MarWelcomeMessage::getCategoryId, categoryIdList);
        lqw.like(StringUtils.isNotBlank(bo.getMessage()), MarWelcomeMessage::getMessage, bo.getMessage());
        lqw.orderByDesc(MarWelcomeMessage::getWelcomeMsgId);
        return lqw;
    }

    /**
     * 新增欢迎语
     */
    @Override
    public Boolean insertByBo(MarWelcomeMessageBo bo) {
        MarWelcomeMessage add = BeanUtil.toBean(bo, MarWelcomeMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setWelcomeMsgId(add.getWelcomeMsgId());
        }
        return flag;
    }

    /**
     * 修改欢迎语
     */
    @Override
    public Boolean updateByBo(MarWelcomeMessageBo bo) {
        MarWelcomeMessage update = BeanUtil.toBean(bo, MarWelcomeMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MarWelcomeMessage entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除欢迎语
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
